<template>
	<basic-container>
		<el-tabs v-model="tabActiveName" @tab-click="handleClick">
			<el-tab-pane label="规格设置" name="first">
				
			</el-tab-pane>
			<el-tab-pane label="自然属性" name="second">
			</el-tab-pane>
		</el-tabs>
		<avue-crud :option="optionsale" :data="datasale" ref="crud" v-model="form" :table-loading="loadingsale" :permission="permissionList"
		:before-open="beforeOpen" :page="page" @select-all="checkedAll" @refresh-change="refreshChange" @search-change="searchChange"
		@search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
		@on-load="onLoad">
			<template slot="menuLeft" slot-scope="row">
				<el-button type="primary" @click="addNew(row)" size="mini" v-has="'/mall-cloud-base/goodsClassSpec/addItem'">
					{{tabActiveName=='first'?'新增规格':'新增属性'}}</el-button>
			</template>
			<template slot-scope="{row,type,size}" slot="menu">
				<el-button :type="type" :size="size" @click="editNew(row)" v-has="'/mall-cloud-base/specification/editItemSelf'">编辑</el-button>
				<el-button :type="type" :size="size" @click="delNew(row)" v-has="'/mall-cloud-base/specification/deleteSelf'">删除</el-button>
				<el-button :type="type" :size="size" v-if="row.parentId == ''" @click="childAddNew(row)" v-has="'/mall-cloud-base/specification/addItem'">{{tabActiveName=='first'?'新增子规格':'新增子属性'}}</el-button>
			</template>
		</avue-crud>
		<el-dialog :title="addTitle"  :visible.sync="newAttribute" width="50%" >
			<el-form ref="addFrom" label-width="80px" :model="addFrom" :rules="addFromrules" size="mini">
				<el-form-item label="规格名称" prop="specName">
					<el-col :span="18">
						<el-input v-model="addFrom.specName" placeholder="请输入规格名称"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="排序" prop="specSequence">
					<el-col :span="18">
						<el-input v-model="addFrom.specSequence" placeholder="请输入排序号" onkeyup="value=value.replace(/\s/g,'')"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="规格类型" prop="specModule">
					<el-radio-group v-model="addFrom.specModule">
						<el-radio label="text">文字</el-radio>
						<el-radio label="img" v-if="tabActiveName=='first'">图片</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="addpantentAndchild('addFrom')"  :loading="btnloading" size="mini">提交</el-button>
				<el-button type="default" @click="clearAddfrom" size="mini">清空</el-button>
			</span>
		</el-dialog>

		<el-dialog title="编辑" :visible.sync="editData" width="50%">
			<el-form :model="editForm" ref="editForm" label-width="80px" :rules="editrules" size="mini">
				<!--编辑父类才展示的-->
				<el-form-item label="规格名称" v-if="isParent" prop="specName">
					<el-col :span="22">
						<el-input v-model="editForm.specName" placeholder="请输入规格名称"></el-input>
					</el-col>
				</el-form-item>
				<!--编辑父类才展示的(父类的排序)-->
				<el-form-item v-if="isParent" label="排序" prop="specSequence">
					<el-col :span="22">
						<el-input maxlength="6" v-model="editForm.specSequence" @input="change($event)" placeholder="请输入排序号"></el-input>
					</el-col>
				</el-form-item>
				<!--编辑子类才展示的(子类的排序)-->
				<el-form-item v-if="!isParent" maxlength="6" label="排序" prop="specpSequence">
					<el-col :span="22">
						<el-input v-model="editForm.specpSequence" @input="changes($event)" placeholder="请输入排序号"></el-input>
					</el-col>
				</el-form-item>
                <!--编辑父类才展示的-->
				<el-form-item label="规格类型" v-if="isParent">
					<el-radio-group v-model="editForm.specModule">
						<el-radio label="text">文字</el-radio>
						<el-radio label="img" v-if="editForm.specType==0">图片</el-radio>
					</el-radio-group>
				</el-form-item>
				<!--编辑子类才展示的-->
				<el-form-item label="规格值" prop="specpValue" v-if="!isParent">
					<el-col :span="22">
						<el-input v-model="editForm.specpValue" placeholder="请输入规格值"></el-input>
					</el-col>
				</el-form-item>

				<el-form-item label="图片" v-if="isspecvalue">
					<el-image style="width: 100px; height: 100px" :src="editForm.specImageUrl">
						<div  slot="error" class="image-slot">
							<i class="el-icon-picture-outline"></i>
						</div>
					</el-image>
				</el-form-item>
				<el-form-item v-if="isspecvalue">
					<el-button type="primary" size="mini" @click="uploadimg">上传图片</el-button>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submit('editForm')" size="mini" :loading="loadBtn">提交</el-button>
				<el-button type="default" @click="clearEditfrom" size="mini">清空</el-button>
			</span>
		</el-dialog>

		<el-dialog :title="addChildTitle" ref="addchildprop" :visible.sync="childdialog" width="50%">
			<el-form :model="childData" :rules="childrules" ref="childData" label-width="80px" size="mini">
				<el-form-item label="排序" prop="specpSequence">
					<el-col :span="22">
						<el-input maxlength="6" v-model="childData.specpSequence"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="规格值" prop="specpValue">
					<el-col :span="22">
						<el-input v-model="childData.specpValue"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="图片" v-if="childData.specModule == 'img'">
					<el-image style="width: 100px; height: 100px" :src="childData.specImageUrl">
						<div  slot="error" class="image-slot">
							<i class="el-icon-picture-outline"></i>
						</div>
					</el-image>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-if="childData.specModule == 'img'" @click="uploadimg">上传图片</el-button>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handlechildsubmit('childData')" size="mini" :loading="loadBtnchild" v-has="'/mall-cloud-base/specification/addItem'">提交</el-button>
				<el-button type="default" @click="clearAddfrom" size="mini">清空</el-button>
			</span>
		</el-dialog>
		<sel-file @callback="selFileCallBack" ref="selFile" albumCode="pic_root" dialogTitle="选择图片" selectType="radio"
		selMaxWidth="300px" selMaxHeight="300px"></sel-file>
	</basic-container>
</template>
<script>
	import {
		getList,
		removeSelf,
		add,
		remove,
		updateParent
	} from "@/api/base/goods/specification";
	import {
		isInteger,
		testSort,
		validateSpace,
		testSpeValue,
		testSpecName
	} from '@/util/util'
	import selFile from '@/components/file/selFile'
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				addTitle:'',
				addChildTitle:'',
				loadBtnchild:false,
				loadBtn:false,
				btnloading:false,
				newSpecName:'',
				deldata: [], //全选删除
				isspecvalue: false,
				isParent: false, //是否父属性
				childdialog: false, //新增子规格
				childData: {
					specpValue: '', //规格值
					specImageUrl: '', //图片
					specpSequence:'',//排序号
				},
				childrules: {
					specpValue: [{
						required: true,
						message: '请输入规格值',
						trigger: 'blur'
					},{
						required: true,
						validator:testSpeValue,
						trigger: 'blur'
					} ],
					specImageUrl: [{
						required: true,
						message: '请上传图片'
					}],
					specpSequence: [{
							required: true,
							message: '请输入排序号',
							trigger: 'blur'
						},{
						required:true,
						validator:validateSpace,
						trigger:'blur'
					},
						{
							required: true,
							validator: testSort,
							trigger: 'blur'
						},
					]
				},
				addFrom: {
					specName: '', //父属性名
					specSequence: '', //父属性排序
					specImageUrl: '',
					specModule: 'text', //父属性规格类型
                    specpSequence:'',//子属性排序
                    specpValue:''//子属性值
				}, //新增父子属性数据
				addFromrules: {
					specName: [{
						required: true,
						message: '请输入属性名',
						trigger: 'blur'
					},{
						required: true,
						validator:testSpecName,
						trigger:'blur'
					}],
					specSequence: [{
							required: true,
							message: '请输入属性排序号',
							trigger: 'blur'
						},
						{
							validator: testSort,
							trigger: 'blur'
						}, {
							max: 6,
							message: '最长6个字符',
							trigger: 'blur' },

					],
					specModule: [{
						required: true,
						message: '请选择规格类型',
						trigger: 'blur'
					}],
				},
				editForm: {
					specSequence: '', //父属性排序
					specpSequence: '', //子属性排序
					specName: '', //规格名称
					specImageUrl: '', //图片
					specValue: '', //属性值
					specpValue: '', //规格值
					specModule: '' //规格类型
				}, //编辑弹窗form表单数据
				editrules: {
					specSequence: [{
							required: true,
							message: '请输入排序号',
							trigger: 'blur'
						},
						{
							required: true,
							validator: testSort,
							trigger: 'blur'
						},{
							required: true,
							validator: validateSpace,
							trigger:'blur'
						}
					],
					specpSequence: [{
						required: true,
						message: '请输入排序号',
						trigger: 'blur'
					},{
						required: true,
						validator: validateSpace,
						trigger:'blur'
					}, {
							required: true,
							validator: testSort,
							trigger: 'blur'
						},
					],
					specName: [{
						required: true,
						message: '请输入规格名称',
						trigger: 'blur'
					},{
						validator:testSpecName,
						trigger:'blur'
					}],
					specpValue: [{
						required: true,
						message: '请输入规格值',
						trigger: 'blur'
					},{
						required:true,
						validator:testSpeValue,
						trigger:'blur'
					}]
				},
				spectab: 'parent',
				tabActiveName: 'first', //tab页切换
				specType: '0', //规格设置
				checkAllData: [],
				form: {},
				query: {},
				loadingsale: true,
				loadingnature: true,
				newAttribute: false,
				editData: false,
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				optionsale: {
					// defaultSort:{
					// 	prop: 'specSequence',
					// 	order: 'ascending'
					// },
					size: 'mini',
					excelBtn: false,
					border: true,
					addBtn: false,
					editBtn: false,
					delBtn: false,
					viewBtn: false,
					rowKey: 'id',
					height: 'auto',
					calcHeight: 380,
					align: 'center',
					menuWidth: 200,
					searchMenuSpan:6,
					treeProps: {
						children: 'childrenNodes',
						defaultSort:{
							prop: 'specSequence',
							order: 'ascending'
						},
					},
					column: [{
							label: "排序",
							sortable:false,
							prop: "specSequence",
							fixed: true,
							rules: [{
								required: true,
								message: "请输入排序字段  序号越小越靠前",
								trigger: "blur"
							}]
						},
						{
							label: "规格名称",
							prop: "specName",
							search: true,
						},
						{
							label: "规格值",
							prop: "specpValue",
						}
					]
				},
				optionnature: {
					size: 'mini',
					excelBtn: false,
					border: true,
					selection: true,
					rowKey: 'id',
					height: 'auto',
					// calcHeight: 380,
					align: 'center',
					menuWidth: 250,
					treeProps: {
						children: 'childrenNodes'
					},
					column: [{
							label: "排序",
							prop: "specSequence",
							fixed: true,
							rules: [{
								required: true,
								message: "请输入排序字段  序号越小越靠前",
								trigger: "blur"
							}]
						},
						{
							label: "规格名称",
							prop: "specName",
							search: true,
						},
						{
							label: "规格值",
							prop: "specpValue"
						}
					]
				},
				datasale: [],
				datanature: [],
			};
		},
		components: {
			selFile
		},
		watch: {
			'specType'(val) {
				console.log(val)
				this.onLoad(this.page)
			},
			
			newAttribute(val){
				if(!val){
					this.$refs["addFrom"].resetFields();
					this.btnloading=false
				}
			},
			childdialog(val){
				if(!val){
					this.$refs["childData"].resetFields();
					this.loadBtnchild=false
				}
			},
			editData(val){
				if(!val){
					this.$refs["editForm"].resetFields();
				}
			}

		},
		computed: {
			...mapGetters(["permission", 'userInfo']),
			permissionList() {
				return {

				};
			},
		},
		methods: {
			change(e){
				this.editForm.specSequence = e;
			    this.$forceUpdate();
			},
			changes(e){
				this.editForm.specSequence = e;
			    this.$forceUpdate();
			},
			//处理新增子规格提交事件
			handlechildsubmit(childData) {
				this.$nextTick(()=>{
					this.$refs["childData"].clearValidate();
				})
				this.childData.define = 0
				this.childData.specType = this.specType
				console.log(this.childData)
				this.$refs[childData].validate((valid) => {
					if (valid) {
						this.loadBtnchild=true
						add(this.childData)
							.then(res => {
								if (res.data.code == 200) {
									this.$message.success('添加成功')
									this.onLoad(this.page);
									this.$nextTick(()=>{
										this.$refs["childData"].resetFields();
									})
									this.childdialog = false;
									this.loadBtnchild=false
								}else if(res.data.code==201) {
									this.$confirm(res.data.message, '提示', {
										confirmButtonText: '确定',
										cancelButtonText: '取消',
										type: 'warning'
									}).then(() => {
										this.childData.define = 1
										add(this.childData).then(res=>{
											if(res.data.code==200) {
												this.$message.success('添加成功')
												this.onLoad(this.page);
												this.$nextTick(()=>{
													this.$refs["childData"].resetFields();
												})
												this.childdialog = false;
												this.loadBtnchild=false
											}else {
												this.loadBtnchild=false
												this.$message.error(res.data.message);
												return;
											}
										})
									}).catch(() => {
										this.$message({
											type: 'info',
											message: '已取消新增'
										});
									});
								}
								else {
									this.loadBtnchild=false
									this.$message.error(res.data.message);
									return;
								}
							})
							.catch(err => {
								this.$message.error(err);
								this.loadBtnchild=false;
								return;
							})
					} else {
						this.loadBtnchild=false;
						this.$message({
							type: "error",
							message: "请先填写必要信息!"
						});
						return false
					}
				})

			},
			submit(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.loadBtn=true
						this.editForm.define = 0
						updateParent(Object.assign(this.editForm, {
								specType: this.specType
							}))
							.then(res => {
								if (res.data.code == 200) {
									this.loadBtn=false
									this.$message.success('修改成功');
									this.onLoad(this.page);
									this.editData = false;
									this.clearAddfrom();
								}else if(res.data.code==201) {

									this.$confirm(res.data.message, '提示', {
										confirmButtonText: '确定',
										cancelButtonText: '取消',
										type: 'warning'
									}).then(() => {
										this.editForm.define = 1
										updateParent(Object.assign(this.editForm, {
											specType: this.specType
										})).then(res=>{
											if(res.data.code==200) {
												this.loadBtn=false
												this.$message.success('修改成功');
												this.onLoad(this.page);
												this.editData = false;
												this.clearAddfrom();
											}else {
												this.loadBtn=false
												this.$message.error(res.data.message);
												return;
											}
										})
									}).catch(() => {
										this.$message({
											type: 'info',
											message: '已取消新增'
										});
									});
								}else {
									this.loadBtn=false
									this.$message.error(res.data.message);
								}

							})
							.catch(err => {
								this.$message.error(err);
							})
					} else {
						return false
					}
				})
			},
            //该方法用于只新增父属性
			addpantentAndchild(addFrom) {
				this.$nextTick(()=>{
					this.$refs["addFrom"].clearValidate();
				})
				this.$refs[addFrom].validate((valid) => {
					if (valid) {
						this.btnloading = true;
						if(!this.addFrom.specModule){
							this.$message({
								message: '请选择规格类型',
								type: 'error'
							});
							this.btnloading = false;
							return false;
						}
						console.log(this.addForm);
						add(Object.assign(this.addFrom, {
								specType: this.specType
							})).then(res => {
								if (res.data.code == 200) {
									this.$nextTick(()=>{
										this.$refs["addFrom"].resetFields();
									})
									this.btnloading = false;
									this.$message.success('成功');
									this.onLoad(this.page);
									this.newAttribute = false;
									this.btnloading=false
								}
								else {
									this.btnloading = false;
									this.$message.error(res.data.message);
									return;
								}
							})
							.catch(err => {
								this.btnloading = false;
								this.$message.error(err);
							})
					} else {
						this.btnloading = false;
						this.$message({
							type: "error",
							message: "请先填写必要信息!"
						});
						return false
					}
				})
			},
			clearAddfrom() {
				this.addFrom = {
					specName: '', //父属性名
					specSequence: '', //父属性排序
					specImageUrl: '',
					specModule: 'text', //父属性规格类型
                    specpSequence:'',//子属性排序
                    specpValue:''//规格值
				};
				this.editForm = {
					specSequence: '', //排序
					specName: '', //规格名称
					specImageUrl: '', //图片
					specValue: '', //属性值
					specpValue: '', //规格值
					specModule: '' //规格类型
				};
				this.childData = {
					specpValue: '', //规格值
					specImageUrl: '', //图片
					specpSequence:'',//排序号
					specModule: this.childData.specModule,
					specName: this.childData.specName,
				};
				this.loadBtn=false;
				this.loadBtnchild=false;
				this.btnloading=false;
			},
			clearEditfrom(){
				if (this.isParent){
					this.editForm.specSequence = '';
					this.editForm.specName = '';
					this.editForm.specModule='text'
				}else{
				    this.editForm.specpSequence = '';
					this.editForm.specImageUrl = '';
					this.editForm.specpValue = '';
				}
			},
			selFileCallBack(data) {
				//上传图片插件回传的数据
				this.$nextTick(()=>{
					this.addFrom.specImageUrl = data[0]
					this.editForm.specImageUrl = data[0]
					this.childData.specImageUrl = data[0]
				})

			},
			uploadimg() {
				//上传图片
				this.$refs.selFile.open()
			},
			//规格设置，自然属性tab切换
			handleClick(tab) {
				//tab页切换
				if (tab.name == "first") {
					this.specType = '0'; //规格设置
					this.currentChange(1)
					this.onLoad(this.page);
				} else if (tab.name == "second") {
					this.specType = '1'; //自然属性
					this.currentChange(1)
					this.onLoad(this.page);
				}
				this.$refs.crud.searchReset()
				this.query = {}
				console.log(this.specType);
			},
			addNew() {
				if(this.tabActiveName=='first'){
					this.addTitle='新增规格'
				}else{
					this.addTitle='新增属性'
				}
				//全数据新增(既可以一个新的规格，以及该规格下的子属性)
				this.newAttribute = true
				//打开新增的页面时清空图片预览数据
				this.addFrom.specImageUrl = ''
				this.editForm.specImageUrl = ''
				this.childData.specImageUrl = ''
			},
			childAddNew(row) {
				if(this.tabActiveName=='first'){
					this.addChildTitle='新增子规格'
				}else{
					this.addChildTitle='新增子属性'
				}
				//新增子规格事件
				this.childdialog = true
				this.childData.specName = row.specName
				this.childData.specModule = row.specModule
				this.childData.parentId = row.id
				this.childData.specImageUrl = ''
			},
			editNew(row) {
				
				//行编辑
				this.editData = true
				this.editForm.specModule = row.specModule || '';
                this.editForm.specType = row.specType || '';
				if ('childrenNodes' in row) {
					this.editForm.id = row.id || '';
					this.editForm.specpropertyId = '';
					this.editForm.specModule = row.specModule || '';
					this.editForm.specSequence = row.specSequence || ''
					this.editForm.specName = row.specName || ''
					this.editForm.specValue = row.specValue || ''
					this.isParent = true;
					this.isspecvalue = false;
				} else {
					this.editForm.specSequence = row.specpSequence || ''
					this.editForm.specpSequence = row.specpSequence || ''
					this.editForm.specName = row.specName || ''
					this.editForm.specImageUrl = row.specImageUrl || ''
					this.editForm.specValue = row.specValue || ''
					this.editForm.specpValue = row.specpValue || ''
					this.editForm.id = row.parentId || ''
					this.editForm.specpropertyId = row.id || ''
					this.isParent = false;
					if (row.specModule == 'img') {
						this.isspecvalue = true;
					} else {
						this.isspecvalue = false;
					}
				}
				console.log(this.editForm)
			},
			delNew(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return removeSelf(row.id, row.parentId)
							.then(res => {
								if (res.data.success) {
									this.$message.success('删除成功')
									if (this.specType == '0') { //规格设置
										if (this.datasale.length == 1) {
											this.page.currentPage -= 1
										}
									} else { //自然属性
										if (this.datanature.length == 1) {
											this.page.currentPage -= 1
										}
									}
									if (this.datasale.length == 1) {
										this.page.currentPage -= 1
									}
									this.onLoad(this.page)

								}
								else{
                                    this.$message.error(res.data.message);
								}
							})
							.catch(() => {
								this.$message({
									type: 'info',
									message: '已取消删除'
								})
							})
					})
			},
			delAll() {
				//批量删除
				if (this.deldata.length > 0) {
					// this.$refs.crud.toggleSelection(this.data)
					this.$confirm("确定将选择数据删除?", {
							confirmButtonText: "确定",
							cancelButtonText: "取消",
							type: "warning"
						})
						.then(() => {
							return remove(this.deldata)
						})
						.then((res) => {
							if (res.data.code == 200) {
								this.onLoad(this.page);
								this.$message({
									type: "success",
									message: "操作成功!"
								});
							}
						})
				}else{
					this.$message.error('请选择删除的属性');
				}
			},
			selectionChange(data) {
				this.deldata = this.handleData(data)
			},
			checkedAll(selection) {
				this.deldata = this.handleData(selection)
			},
			handleData(data) {
				let arr = data.map(item => {
					return item.id.toString()
				})
				return arr
			},
			searchReset() {
				this.deldata = []
				this.$refs.crud.toggleSelection();
				this.query = {};
				this.newSpecName = "";
				this.onLoad(this.page);
			},
			searchChange(params,done) {
				if(params.specName){
					this.newSpecName = params.specName;
				}
				this.deldata = []
				this.$refs.crud.toggleSelection();
				this.page.currentPage=1
				params.specType = this.specType
				this.onLoad(this.page, params,done);
			},
			beforeOpen(done, type) {
				if (["edit", "view"].includes(type)) {
					getList(this.form.id).then(res => {
						this.form = res.data.data;
					});
				}
				done();

			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.deldata = []
				this.$refs.crud.toggleSelection();
				this.onLoad(this.page);
			},
			onLoad(page, params = {specType: this.specType},done) {
				if(!params.specName && this.newSpecName){
					params.specName = this.newSpecName;
				}
				// if (this.specType == '0') {
					this.loadingsale = true;
					getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
						if(done){
							done();
						}
						this.loadingsale = false;
						this.page.total = res.data.count;
						this.datasale = res.data.data.map(item => {
							let specValue = []
							item.childrenNodes.forEach(ele => {
								specValue.push(ele.specpValue)
								ele.specSequence = ele.specpSequence
							})
							item.specpValue = specValue.join(',')
							return item
						})
						console.log(this.datasale)
					});

				// } else if (this.specType == '1') {
				// 	this.loadingnature = true;
				// 	console.log(this.page.currentPage)
				// 	getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				// 		this.loadingnature = false;
				// 		this.page.total = res.data.count;
				// 		this.datanature = res.data.data.map(item => {
				// 			let specValue = []
				// 			item.childrenNodes.forEach(ele => {
				// 				specValue.push(ele.specpValue)
				// 				ele.specSequence = ele.specpSequence
				// 			})
				// 			item.specpValue = specValue.join(',')
				// 			return item
				// 		})

				// 	});
				// }


			},
		}
	};
</script>

<style scoped>
	.el-icon-picture-outline{
		font-size: 100px;
	}
</style>
